import React, { Component } from "react";
import { Bubble, Tools } from "weaver-mobile";
import { withRouter, Route } from 'react-router-dom';
import { getImgUrl, formParamsTransToStyle, pWidth, pHeight } from "./util/index";
import { RouteLayout } from "weaver-mobile-page";
import SendBless from "../sendBless/index";
import "./style/index.less";

const getLabel = Tools.getLabel;

@withRouter
export default class HappyBirthday extends Component {
    constructor(props) {
        super(props);

        this.basicStyle = { width: "100%", height: "100%" };

        this.state = {
            visible: false,
            bg_datas: {},
            congratulation_datas: {},
            date_data: {},
            head_bar_datas: {},
            head_datas: {},
            img_datas: {},
            person_datas: {},
            personList: [],
            createDate: "",
            defaultImg: "",
            displaySetting: "1;1",
            layout : new RouteLayout.Store({ route: "/birthdayRemind" ,id:"sendBless"}),
            recordId:''
        }
    }

    componentDidMount() {
        const { match: { params: { id } } } = this.props;
        this.setState({recordId: id})
        this.getBirthInfo(id);
    }

    getBirthInfo = (recordId) => {
        Tools.callApi({
            url: "/api/hrm/birthday/readBirthdayRemindData",
            method: 'GET',
            params: { recordId }
        }).then(res => {
            if (res.status == "1") {
                Object.keys(this.state).forEach(key => {
                    if (res[key]) {
                        this.setState({
                            [key]: res[key]
                        })
                    }
                });
                //TODO 
                this.setState({
                    defaultImg: "/hrm/hrm_e9/image/u59.png"
                });
                this.setState({ visible: true });
            } else {
                Bubble.error(res.message);
            }
        })
    }

    render() {
        const { visible, bg_datas, img_datas, head_datas, congratulation_datas, date_data, person_datas, displaySetting, createDate, personList, defaultImg, layout } = this.state;

        const {history} = this.props;

        const isBirthDateShow = displaySetting.split(";")[0].split(",").includes("2");

        if (!visible) return null;

        return (
            <div className="happy-birthday">
                <Bg datas={{bg_datas, defaultImg,...this.basicStyle}}/>
                <Img datas={img_datas}/>
                <Text datas={head_datas}/>
                <Congratulation datas={congratulation_datas}/>
                <BirthDate datas={date_data} isShow={isBirthDateShow} date={createDate}/>
                <PersonInfo datas={person_datas} personList={personList} displaySetting={displaySetting.split(";")[1]} date={createDate} history={history} layout={layout} recordId={this.state.recordId}/>
            </div>
        );
    }
}

const getStyle = (datas) => {
    const { formParams, id, isAbsolute, defaultImg } = datas;
    const style = {};
    if (isAbsolute) {
        style.position = "absolute";
    }
    if (id) {
        style.backgroundImage = `url(${getImgUrl(id,defaultImg)})`
    }
    if (formParams) {
        Object.keys(formParams).forEach(key => {
            Object.assign(style, formParamsTransToStyle(key, formParams))
        });
    }
    return style;
}

class Bg extends Component {
    render() {
        const { datas: { bg_datas: { form_params, selectedid } = {}, defaultImg, width, height } } = this.props;

        const style = { width, height };
        Object.assign(style, getStyle({ formParams: form_params, id: selectedid, isAbsolute: true, defaultImg }));
        return <div style={style}/>
    }
}


class Img extends Component {
    render() {
        const { datas: { form_params, id } } = this.props;

        return id ? <div style={{...getStyle({formParams:form_params,id, isAbsolute:true}), backgroundSize: "100%"}}/> : null;
    }
}

class Text extends Component {
    render() {
        const { datas: { form_params, title } } = this.props;

        return title ? <div style={getStyle({formParams:form_params,isAbsolute:true})} dangerouslySetInnerHTML = {{ __html: title }}/> : null;
    }
}

class Congratulation extends Component {
    render() {
        const { datas: { form_params, paragraph } } = this.props;

        return paragraph ? <div style={getStyle({formParams:form_params,isAbsolute:true})} dangerouslySetInnerHTML = {{ __html: paragraph }}/> : null;

    }
}

class BirthDate extends Component {
    render() {
        const { datas: { form_params }, date, isShow } = this.props;

        return isShow ? <div style={getStyle({formParams:form_params,isAbsolute:true})}>{date}</div> : null;
    }
}

class PersonInfo extends Component {
    sendLove = (id) => {
        this.targetId = id;
        const{history,layout} = this.props;
        history.push(layout.path);
    }

    handleNameClick = (id) => {
        if (window.em != null && window.em.checkJsApi('openLink')) {
            window.em.openLink({
                url: `/spa/hrm/static4mobile/index.html#/resourceInfo/${id}`,
                openType: 2,
                sysId: window.localStorage.emobile_ec_id
            });
        } else {
            window.location.href = `/spa/hrm/static4mobile/index.html#/resourceInfo/${id}`;
        }
    }

    render() {
        const { datas: { form_params }, personList, displaySetting ,layout,date,history,recordId} = this.props;

        const displayItems = [];

        const obj = {
            "1": "lastname",
            "2": "departmentName",
            "3": "subCompanyName",
            "4": "sendLove"
        };

        displaySetting.split(",").sort().forEach(v => {
            if (["1", "4"].includes(v)) {
                displayItems.push(obj[v]);
            }
            if (["2", "3"].includes(v)) {
                const tarIndex = displayItems.findIndex(item => typeof item == "object");
                if (tarIndex == -1) {
                    displayItems.push([obj[v]]);
                } else {
                    const tarArr = displayItems[tarIndex];
                    tarArr.push("connector");
                    tarArr.push(obj[v]);
                }
            }
        })

        return personList.length > 0 && (
            <div style={{...getStyle({formParams: form_params, isAbsolute: true}), width: pWidth, height: pHeight}} className="person-view">
                {personList.map(info => {
                    const _info = Object.assign({}, info, {
                        sendLove: getLabel(529679, '送祝福'),
                        connector: "-"
                    })
                    return (
                        <p>
                            {displayItems.map(v => {
                                if (typeof v == "string") {
                                    return (
                                        <span className={v} onClick={() =>(v == "sendLove") && this.sendLove(info.id) }  style={(v == "sendLove") ? {color: form_params["btn-color"]}: {}}>
                                            { (v == "sendLove")  ? _info[v] : <a onClick={() => this.handleNameClick(info.id)}>{_info[v]}</a>}
                                        </span>
                                    )
                                }else{
                                    return (
                                        <span className="org">
                                            {v.map(key => {
                                                return (
                                                    <span className={key}>{_info[key]}</span>
                                                )
                                            })}
                                        </span>
                                    )
                                }
                            })}
                        </p>
                    )
                })}
                <Route
                  key={layout.id}
                  path={layout.path}
                  render={() => (
                    <RouteLayout>
                      <div
                        key="wmPoutePageDemo"
                        className="wm-route-layout wm-demo-route-layout-page"
                      >
                        <SendBless personDatas={personList.map(data => ({id:data.id,name:data.lastname}) )} targetId={this.targetId} createDate={date} history={history} recordId={recordId}/>
                      </div>
                    </RouteLayout>
                  )}
                />
            </div>
        )
    }
}